import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

class MyDragWidget extends StatefulWidget{
  @override
  _MyDragState createState() => _MyDragState();

}

class _MyDragState extends State<MyDragWidget>{

  double dx = 0;
  double dy = 0;
  final mykey = new GlobalKey<_MyDragState>();

  @override
  Widget build(BuildContext context) {
    return  GestureDetector(
      onHorizontalDragUpdate: dragEvent,
      onVerticalDragUpdate: dragEvent,
      child: Container(
        color: Colors.red,
        child: Transform.translate(
          offset: Offset(dx, dy),
          child: Align(
            alignment: Alignment.topLeft,
            child: Container(
              width: 150.0,
              height: 100.0,
              alignment: Alignment.center,
              key: mykey,
              color: Colors.yellow,
              child: Text("Drag Box"),
            ),
          ),
        ),
      ),
    );
  }

  void dragEvent(DragUpdateDetails details) {
    final RenderObject box = context.findRenderObject();
    //  获得自定义Widget的大小，用来计算Widget的中心锚点
    dx = details.globalPosition.dx - mykey.currentContext.size.width / 2;
    dy = details.globalPosition.dy - mykey.currentContext.size.height / 2;
    setState(() {});
  }

}